home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.5 / doctest.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-05-11  |  75.2 KB  |  2,283 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''Module doctest -- a framework for running examples in docstrings.
  5.  
  6. In simplest use, end each module M to be tested with:
  7.  
  8. def _test():
  9.     import doctest
  10.     doctest.testmod()
  11.  
  12. if __name__ == "__main__":
  13.     _test()
  14.  
  15. Then running the module as a script will cause the examples in the
  16. docstrings to get executed and verified:
  17.  
  18. python M.py
  19.  
  20. This won\'t display anything unless an example fails, in which case the
  21. failing example(s) and the cause(s) of the failure(s) are printed to stdout
  22. (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
  23. line of output is "Test failed.".
  24.  
  25. Run it with the -v switch instead:
  26.  
  27. python M.py -v
  28.  
  29. and a detailed report of all examples tried is printed to stdout, along
  30. with assorted summaries at the end.
  31.  
  32. You can force verbose mode by passing "verbose=True" to testmod, or prohibit
  33. it by passing "verbose=False".  In either of those cases, sys.argv is not
  34. examined by testmod.
  35.  
  36. There are a variety of other ways to run doctests, including integration
  37. with the unittest framework, and support for running non-Python text
  38. files containing doctests.  There are also many ways to override parts
  39. of doctest\'s default behaviors.  See the Library Reference Manual for
  40. details.
  41. '''
  42. __docformat__ = 'reStructuredText en'
  43. __all__ = [
  44.     'register_optionflag',
  45.     'DONT_ACCEPT_TRUE_FOR_1',
  46.     'DONT_ACCEPT_BLANKLINE',
  47.     'NORMALIZE_WHITESPACE',
  48.     'ELLIPSIS',
  49.     'SKIP',
  50.     'IGNORE_EXCEPTION_DETAIL',
  51.     'COMPARISON_FLAGS',
  52.     'REPORT_UDIFF',
  53.     'REPORT_CDIFF',
  54.     'REPORT_NDIFF',
  55.     'REPORT_ONLY_FIRST_FAILURE',
  56.     'REPORTING_FLAGS',
  57.     'Example',
  58.     'DocTest',
  59.     'DocTestParser',
  60.     'DocTestFinder',
  61.     'DocTestRunner',
  62.     'OutputChecker',
  63.     'DocTestFailure',
  64.     'UnexpectedException',
  65.     'DebugRunner',
  66.     'testmod',
  67.     'testfile',
  68.     'run_docstring_examples',
  69.     'Tester',
  70.     'DocTestSuite',
  71.     'DocFileSuite',
  72.     'set_unittest_reportflags',
  73.     'script_from_examples',
  74.     'testsource',
  75.     'debug_src',
  76.     'debug']
  77. import __future__
  78. import sys
  79. import traceback
  80. import inspect
  81. import linecache
  82. import os
  83. import re
  84. import unittest
  85. import difflib
  86. import pdb
  87. import tempfile
  88. import warnings
  89. from StringIO import StringIO
  90. OPTIONFLAGS_BY_NAME = { }
  91.  
  92. def register_optionflag(name):
  93.     return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
  94.  
  95. DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
  96. DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
  97. NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
  98. ELLIPSIS = register_optionflag('ELLIPSIS')
  99. SKIP = register_optionflag('SKIP')
  100. IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
  101. COMPARISON_FLAGS = DONT_ACCEPT_TRUE_FOR_1 | DONT_ACCEPT_BLANKLINE | NORMALIZE_WHITESPACE | ELLIPSIS | SKIP | IGNORE_EXCEPTION_DETAIL
  102. REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
  103. REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
  104. REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
  105. REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
  106. REPORTING_FLAGS = REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF | REPORT_ONLY_FIRST_FAILURE
  107. BLANKLINE_MARKER = '<BLANKLINE>'
  108. ELLIPSIS_MARKER = '...'
  109.  
  110. def _extract_future_flags(globs):
  111.     '''
  112.     Return the compiler-flags associated with the future features that
  113.     have been imported into the given namespace (globs).
  114.     '''
  115.     flags = 0
  116.     for fname in __future__.all_feature_names:
  117.         feature = globs.get(fname, None)
  118.         if feature is getattr(__future__, fname):
  119.             flags |= feature.compiler_flag
  120.             continue
  121.     
  122.     return flags
  123.  
  124.  
  125. def _normalize_module(module, depth = 2):
  126.     '''
  127.     Return the module specified by `module`.  In particular:
  128.       - If `module` is a module, then return module.
  129.       - If `module` is a string, then import and return the
  130.         module with that name.
  131.       - If `module` is None, then return the calling module.
  132.         The calling module is assumed to be the module of
  133.         the stack frame at the given depth in the call stack.
  134.     '''
  135.     if inspect.ismodule(module):
  136.         return module
  137.     elif isinstance(module, (str, unicode)):
  138.         return __import__(module, globals(), locals(), [
  139.             '*'])
  140.     elif module is None:
  141.         return sys.modules[sys._getframe(depth).f_globals['__name__']]
  142.     else:
  143.         raise TypeError('Expected a module, string, or None')
  144.  
  145.  
  146. def _load_testfile(filename, package, module_relative):
  147.     if module_relative:
  148.         package = _normalize_module(package, 3)
  149.         filename = _module_relative_path(package, filename)
  150.         if hasattr(package, '__loader__'):
  151.             if hasattr(package.__loader__, 'get_data'):
  152.                 return (package.__loader__.get_data(filename), filename)
  153.             
  154.         
  155.     
  156.     return (open(filename).read(), filename)
  157.  
  158.  
  159. def _indent(s, indent = 4):
  160.     '''
  161.     Add the given number of space characters to the beginning every
  162.     non-blank line in `s`, and return the result.
  163.     '''
  164.     return re.sub('(?m)^(?!$)', indent * ' ', s)
  165.  
  166.  
  167. def _exception_traceback(exc_info):
  168.     '''
  169.     Return a string containing a traceback message for the given
  170.     exc_info tuple (as returned by sys.exc_info()).
  171.     '''
  172.     excout = StringIO()
  173.     (exc_type, exc_val, exc_tb) = exc_info
  174.     traceback.print_exception(exc_type, exc_val, exc_tb, file = excout)
  175.     return excout.getvalue()
  176.  
  177.  
  178. class _SpoofOut(StringIO):
  179.     
  180.     def getvalue(self):
  181.         result = StringIO.getvalue(self)
  182.         if result and not result.endswith('\n'):
  183.             result += '\n'
  184.         
  185.         if hasattr(self, 'softspace'):
  186.             del self.softspace
  187.         
  188.         return result
  189.  
  190.     
  191.     def truncate(self, size = None):
  192.         StringIO.truncate(self, size)
  193.         if hasattr(self, 'softspace'):
  194.             del self.softspace
  195.         
  196.  
  197.  
  198.  
  199. def _ellipsis_match(want, got):
  200.     """
  201.     Essentially the only subtle case:
  202.     >>> _ellipsis_match('aa...aa', 'aaa')
  203.     False
  204.     """
  205.     if ELLIPSIS_MARKER not in want:
  206.         return want == got
  207.     
  208.     ws = want.split(ELLIPSIS_MARKER)
  209.     if not len(ws) >= 2:
  210.         raise AssertionError
  211.     startpos = 0
  212.     endpos = len(got)
  213.     w = ws[0]
  214.     if w:
  215.         if got.startswith(w):
  216.             startpos = len(w)
  217.             del ws[0]
  218.         else:
  219.             return False
  220.     
  221.     w = ws[-1]
  222.     if w:
  223.         if got.endswith(w):
  224.             endpos -= len(w)
  225.             del ws[-1]
  226.         else:
  227.             return False
  228.     
  229.     if startpos > endpos:
  230.         return False
  231.     
  232.     for w in ws:
  233.         startpos = got.find(w, startpos, endpos)
  234.         if startpos < 0:
  235.             return False
  236.         
  237.         startpos += len(w)
  238.     
  239.     return True
  240.  
  241.  
  242. def _comment_line(line):
  243.     '''Return a commented form of the given line'''
  244.     line = line.rstrip()
  245.     if line:
  246.         return '# ' + line
  247.     else:
  248.         return '#'
  249.  
  250.  
  251. class _OutputRedirectingPdb(pdb.Pdb):
  252.     '''
  253.     A specialized version of the python debugger that redirects stdout
  254.     to a given stream when interacting with the user.  Stdout is *not*
  255.     redirected when traced code is executed.
  256.     '''
  257.     
  258.     def __init__(self, out):
  259.         self._OutputRedirectingPdb__out = out
  260.         pdb.Pdb.__init__(self, stdout = out)
  261.  
  262.     
  263.     def trace_dispatch(self, *args):
  264.         save_stdout = sys.stdout
  265.         sys.stdout = self._OutputRedirectingPdb__out
  266.         
  267.         try:
  268.             return pdb.Pdb.trace_dispatch(self, *args)
  269.         finally:
  270.             sys.stdout = save_stdout
  271.  
  272.  
  273.  
  274.  
  275. def _module_relative_path(module, path):
  276.     if not inspect.ismodule(module):
  277.         raise TypeError, 'Expected a module: %r' % module
  278.     
  279.     if path.startswith('/'):
  280.         raise ValueError, 'Module-relative files may not have absolute paths'
  281.     
  282.     if hasattr(module, '__file__'):
  283.         basedir = os.path.split(module.__file__)[0]
  284.     elif module.__name__ == '__main__':
  285.         if len(sys.argv) > 0 and sys.argv[0] != '':
  286.             basedir = os.path.split(sys.argv[0])[0]
  287.         else:
  288.             basedir = os.curdir
  289.     else:
  290.         raise ValueError("Can't resolve paths relative to the module " + module + ' (it has no __file__)')
  291.     return os.path.join(basedir, *path.split('/'))
  292.  
  293.  
  294. class Example:
  295.     """
  296.     A single doctest example, consisting of source code and expected
  297.     output.  `Example` defines the following attributes:
  298.  
  299.       - source: A single Python statement, always ending with a newline.
  300.         The constructor adds a newline if needed.
  301.  
  302.       - want: The expected output from running the source code (either
  303.         from stdout, or a traceback in case of exception).  `want` ends
  304.         with a newline unless it's empty, in which case it's an empty
  305.         string.  The constructor adds a newline if needed.
  306.  
  307.       - exc_msg: The exception message generated by the example, if
  308.         the example is expected to generate an exception; or `None` if
  309.         it is not expected to generate an exception.  This exception
  310.         message is compared against the return value of
  311.         `traceback.format_exception_only()`.  `exc_msg` ends with a
  312.         newline unless it's `None`.  The constructor adds a newline
  313.         if needed.
  314.  
  315.       - lineno: The line number within the DocTest string containing
  316.         this Example where the Example begins.  This line number is
  317.         zero-based, with respect to the beginning of the DocTest.
  318.  
  319.       - indent: The example's indentation in the DocTest string.
  320.         I.e., the number of space characters that preceed the
  321.         example's first prompt.
  322.  
  323.       - options: A dictionary mapping from option flags to True or
  324.         False, which is used to override default options for this
  325.         example.  Any option flags not contained in this dictionary
  326.         are left at their default value (as specified by the
  327.         DocTestRunner's optionflags).  By default, no options are set.
  328.     """
  329.     
  330.     def __init__(self, source, want, exc_msg = None, lineno = 0, indent = 0, options = None):
  331.         if not source.endswith('\n'):
  332.             source += '\n'
  333.         
  334.         if want and not want.endswith('\n'):
  335.             want += '\n'
  336.         
  337.         if exc_msg is not None and not exc_msg.endswith('\n'):
  338.             exc_msg += '\n'
  339.         
  340.         self.source = source
  341.         self.want = want
  342.         self.lineno = lineno
  343.         self.indent = indent
  344.         if options is None:
  345.             options = { }
  346.         
  347.         self.options = options
  348.         self.exc_msg = exc_msg
  349.  
  350.  
  351.  
  352. class DocTest:
  353.     '''
  354.     A collection of doctest examples that should be run in a single
  355.     namespace.  Each `DocTest` defines the following attributes:
  356.  
  357.       - examples: the list of examples.
  358.  
  359.       - globs: The namespace (aka globals) that the examples should
  360.         be run in.
  361.  
  362.       - name: A name identifying the DocTest (typically, the name of
  363.         the object whose docstring this DocTest was extracted from).
  364.  
  365.       - filename: The name of the file that this DocTest was extracted
  366.         from, or `None` if the filename is unknown.
  367.  
  368.       - lineno: The line number within filename where this DocTest
  369.         begins, or `None` if the line number is unavailable.  This
  370.         line number is zero-based, with respect to the beginning of
  371.         the file.
  372.  
  373.       - docstring: The string that the examples were extracted from,
  374.         or `None` if the string is unavailable.
  375.     '''
  376.     
  377.     def __init__(self, examples, globs, name, filename, lineno, docstring):
  378.         """
  379.         Create a new DocTest containing the given examples.  The
  380.         DocTest's globals are initialized with a copy of `globs`.
  381.         """
  382.         if not not isinstance(examples, basestring):
  383.             raise AssertionError, 'DocTest no longer accepts str; use DocTestParser instead'
  384.         self.examples = examples
  385.         self.docstring = docstring
  386.         self.globs = globs.copy()
  387.         self.name = name
  388.         self.filename = filename
  389.         self.lineno = lineno
  390.  
  391.     
  392.     def __repr__(self):
  393.         if len(self.examples) == 0:
  394.             examples = 'no examples'
  395.         elif len(self.examples) == 1:
  396.             examples = '1 example'
  397.         else:
  398.             examples = '%d examples' % len(self.examples)
  399.         return '<DocTest %s from %s:%s (%s)>' % (self.name, self.filename, self.lineno, examples)
  400.  
  401.     
  402.     def __cmp__(self, other):
  403.         if not isinstance(other, DocTest):
  404.             return -1
  405.         
  406.         return cmp((self.name, self.filename, self.lineno, id(self)), (other.name, other.filename, other.lineno, id(other)))
  407.  
  408.  
  409.  
  410. class DocTestParser:
  411.     '''
  412.     A class used to parse strings containing doctest examples.
  413.     '''
  414.     _EXAMPLE_RE = re.compile('\n        # Source consists of a PS1 line followed by zero or more PS2 lines.\n        (?P<source>\n            (?:^(?P<indent> [ ]*) >>>    .*)    # PS1 line\n            (?:\\n           [ ]*  \\.\\.\\. .*)*)  # PS2 lines\n        \\n?\n        # Want consists of any non-blank lines that do not start with PS1.\n        (?P<want> (?:(?![ ]*$)    # Not a blank line\n                     (?![ ]*>>>)  # Not a line starting with PS1\n                     .*$\\n?       # But any other line\n                  )*)\n        ', re.MULTILINE | re.VERBOSE)
  415.     _EXCEPTION_RE = re.compile("\n        # Grab the traceback header.  Different versions of Python have\n        # said different things on the first traceback line.\n        ^(?P<hdr> Traceback\\ \\(\n            (?: most\\ recent\\ call\\ last\n            |   innermost\\ last\n            ) \\) :\n        )\n        \\s* $                # toss trailing whitespace on the header.\n        (?P<stack> .*?)      # don't blink: absorb stuff until...\n        ^ (?P<msg> \\w+ .*)   #     a line *starts* with alphanum.\n        ", re.VERBOSE | re.MULTILINE | re.DOTALL)
  416.     _IS_BLANK_OR_COMMENT = re.compile('^[ ]*(#.*)?$').match
  417.     
  418.     def parse(self, string, name = '<string>'):
  419.         '''
  420.         Divide the given string into examples and intervening text,
  421.         and return them as a list of alternating Examples and strings.
  422.         Line numbers for the Examples are 0-based.  The optional
  423.         argument `name` is a name identifying this string, and is only
  424.         used for error messages.
  425.         '''
  426.         string = string.expandtabs()
  427.         min_indent = self._min_indent(string)
  428.         output = []
  429.         (charno, lineno) = (0, 0)
  430.         for m in self._EXAMPLE_RE.finditer(string):
  431.             output.append(string[charno:m.start()])
  432.             lineno += string.count('\n', charno, m.start())
  433.             (source, options, want, exc_msg) = self._parse_example(m, name, lineno)
  434.             if not self._IS_BLANK_OR_COMMENT(source):
  435.                 output.append(Example(source, want, exc_msg, lineno = lineno, indent = min_indent + len(m.group('indent')), options = options))
  436.             
  437.             lineno += string.count('\n', m.start(), m.end())
  438.             charno = m.end()
  439.         
  440.         output.append(string[charno:])
  441.         return output
  442.  
  443.     
  444.     def get_doctest(self, string, globs, name, filename, lineno):
  445.         '''
  446.         Extract all doctest examples from the given string, and
  447.         collect them into a `DocTest` object.
  448.  
  449.         `globs`, `name`, `filename`, and `lineno` are attributes for
  450.         the new `DocTest` object.  See the documentation for `DocTest`
  451.         for more information.
  452.         '''
  453.         return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
  454.  
  455.     
  456.     def get_examples(self, string, name = '<string>'):
  457.         '''
  458.         Extract all doctest examples from the given string, and return
  459.         them as a list of `Example` objects.  Line numbers are
  460.         0-based, because it\'s most common in doctests that nothing
  461.         interesting appears on the same line as opening triple-quote,
  462.         and so the first interesting line is called "line 1" then.
  463.  
  464.         The optional argument `name` is a name identifying this
  465.         string, and is only used for error messages.
  466.         '''
  467.         return _[1]
  468.  
  469.     
  470.     def _parse_example(self, m, name, lineno):
  471.         """
  472.         Given a regular expression match from `_EXAMPLE_RE` (`m`),
  473.         return a pair `(source, want)`, where `source` is the matched
  474.         example's source code (with prompts and indentation stripped);
  475.         and `want` is the example's expected output (with indentation
  476.         stripped).
  477.  
  478.         `name` is the string's name, and `lineno` is the line number
  479.         where the example starts; both are used for error messages.
  480.         """
  481.         indent = len(m.group('indent'))
  482.         source_lines = m.group('source').split('\n')
  483.         self._check_prompt_blank(source_lines, indent, name, lineno)
  484.         self._check_prefix(source_lines[1:], ' ' * indent + '.', name, lineno)
  485.         source = []([ sl[indent + 4:] for sl in source_lines ])
  486.         want = m.group('want')
  487.         want_lines = want.split('\n')
  488.         self._check_prefix(want_lines, ' ' * indent, name, lineno + len(source_lines))
  489.         want = []([ wl[indent:] for wl in want_lines ])
  490.         m = self._EXCEPTION_RE.match(want)
  491.         options = self._find_options(source, name, lineno)
  492.         return (source, options, want, exc_msg)
  493.  
  494.     _OPTION_DIRECTIVE_RE = re.compile('#\\s*doctest:\\s*([^\\n\\\'"]*)$', re.MULTILINE)
  495.     
  496.     def _find_options(self, source, name, lineno):
  497.         """
  498.         Return a dictionary containing option overrides extracted from
  499.         option directives in the given source string.
  500.  
  501.         `name` is the string's name, and `lineno` is the line number
  502.         where the example starts; both are used for error messages.
  503.         """
  504.         options = { }
  505.         for m in self._OPTION_DIRECTIVE_RE.finditer(source):
  506.             option_strings = m.group(1).replace(',', ' ').split()
  507.             for option in option_strings:
  508.                 if option[0] not in '+-' or option[1:] not in OPTIONFLAGS_BY_NAME:
  509.                     raise ValueError('line %r of the doctest for %s has an invalid option: %r' % (lineno + 1, name, option))
  510.                 
  511.                 flag = OPTIONFLAGS_BY_NAME[option[1:]]
  512.                 options[flag] = option[0] == '+'
  513.             
  514.         
  515.         if options and self._IS_BLANK_OR_COMMENT(source):
  516.             raise ValueError('line %r of the doctest for %s has an option directive on a line with no example: %r' % (lineno, name, source))
  517.         
  518.         return options
  519.  
  520.     _INDENT_RE = re.compile('^([ ]*)(?=\\S)', re.MULTILINE)
  521.     
  522.     def _min_indent(self, s):
  523.         '''Return the minimum indentation of any non-blank line in `s`'''
  524.         indents = [ len(indent) for indent in self._INDENT_RE.findall(s) ]
  525.  
  526.     
  527.     def _check_prompt_blank(self, lines, indent, name, lineno):
  528.         '''
  529.         Given the lines of a source string (including prompts and
  530.         leading indentation), check to make sure that every prompt is
  531.         followed by a space character.  If any line is not followed by
  532.         a space character, then raise ValueError.
  533.         '''
  534.         for i, line in enumerate(lines):
  535.             if len(line) >= indent + 4 and line[indent + 3] != ' ':
  536.                 raise ValueError('line %r of the docstring for %s lacks blank after %s: %r' % (lineno + i + 1, name, line[indent:indent + 3], line))
  537.                 continue
  538.         
  539.  
  540.     
  541.     def _check_prefix(self, lines, prefix, name, lineno):
  542.         '''
  543.         Check that every line in the given list starts with the given
  544.         prefix; if any line does not, then raise a ValueError.
  545.         '''
  546.         for i, line in enumerate(lines):
  547.             if line and not line.startswith(prefix):
  548.                 raise ValueError('line %r of the docstring for %s has inconsistent leading whitespace: %r' % (lineno + i + 1, name, line))
  549.                 continue
  550.         
  551.  
  552.  
  553.  
  554. class DocTestFinder:
  555.     '''
  556.     A class used to extract the DocTests that are relevant to a given
  557.     object, from its docstring and the docstrings of its contained
  558.     objects.  Doctests can currently be extracted from the following
  559.     object types: modules, functions, classes, methods, staticmethods,
  560.     classmethods, and properties.
  561.     '''
  562.     
  563.     def __init__(self, verbose = False, parser = DocTestParser(), recurse = True, exclude_empty = True):
  564.         '''
  565.         Create a new doctest finder.
  566.  
  567.         The optional argument `parser` specifies a class or
  568.         function that should be used to create new DocTest objects (or
  569.         objects that implement the same interface as DocTest).  The
  570.         signature for this factory function should match the signature
  571.         of the DocTest constructor.
  572.  
  573.         If the optional argument `recurse` is false, then `find` will
  574.         only examine the given object, and not any contained objects.
  575.  
  576.         If the optional argument `exclude_empty` is false, then `find`
  577.         will include tests for objects with empty docstrings.
  578.         '''
  579.         self._parser = parser
  580.         self._verbose = verbose
  581.         self._recurse = recurse
  582.         self._exclude_empty = exclude_empty
  583.  
  584.     
  585.     def find(self, obj, name = None, module = None, globs = None, extraglobs = None):
  586.         """
  587.         Return a list of the DocTests that are defined by the given
  588.         object's docstring, or by any of its contained objects'
  589.         docstrings.
  590.  
  591.         The optional parameter `module` is the module that contains
  592.         the given object.  If the module is not specified or is None, then
  593.         the test finder will attempt to automatically determine the
  594.         correct module.  The object's module is used:
  595.  
  596.             - As a default namespace, if `globs` is not specified.
  597.             - To prevent the DocTestFinder from extracting DocTests
  598.               from objects that are imported from other modules.
  599.             - To find the name of the file containing the object.
  600.             - To help find the line number of the object within its
  601.               file.
  602.  
  603.         Contained objects whose module does not match `module` are ignored.
  604.  
  605.         If `module` is False, no attempt to find the module will be made.
  606.         This is obscure, of use mostly in tests:  if `module` is False, or
  607.         is None but cannot be found automatically, then all objects are
  608.         considered to belong to the (non-existent) module, so all contained
  609.         objects will (recursively) be searched for doctests.
  610.  
  611.         The globals for each DocTest is formed by combining `globs`
  612.         and `extraglobs` (bindings in `extraglobs` override bindings
  613.         in `globs`).  A new copy of the globals dictionary is created
  614.         for each DocTest.  If `globs` is not specified, then it
  615.         defaults to the module's `__dict__`, if specified, or {}
  616.         otherwise.  If `extraglobs` is not specified, then it defaults
  617.         to {}.
  618.  
  619.         """
  620.         if name is None:
  621.             name = getattr(obj, '__name__', None)
  622.             if name is None:
  623.                 raise ValueError("DocTestFinder.find: name must be given when obj.__name__ doesn't exist: %r" % (type(obj),))
  624.             
  625.         
  626.         if module is False:
  627.             module = None
  628.         elif module is None:
  629.             module = inspect.getmodule(obj)
  630.         
  631.         
  632.         try:
  633.             if not inspect.getsourcefile(obj):
  634.                 pass
  635.             file = inspect.getfile(obj)
  636.             source_lines = linecache.getlines(file)
  637.             if not source_lines:
  638.                 source_lines = None
  639.         except TypeError:
  640.             source_lines = None
  641.  
  642.         if globs is None:
  643.             if module is None:
  644.                 globs = { }
  645.             else:
  646.                 globs = module.__dict__.copy()
  647.         else:
  648.             globs = globs.copy()
  649.         if extraglobs is not None:
  650.             globs.update(extraglobs)
  651.         
  652.         tests = []
  653.         self._find(tests, obj, name, module, source_lines, globs, { })
  654.         tests.sort()
  655.         return tests
  656.  
  657.     
  658.     def _from_module(self, module, object):
  659.         '''
  660.         Return true if the given object is defined in the given
  661.         module.
  662.         '''
  663.         if module is None:
  664.             return True
  665.         elif inspect.isfunction(object):
  666.             return module.__dict__ is object.func_globals
  667.         elif inspect.isclass(object):
  668.             return module.__name__ == object.__module__
  669.         elif inspect.getmodule(object) is not None:
  670.             return module is inspect.getmodule(object)
  671.         elif hasattr(object, '__module__'):
  672.             return module.__name__ == object.__module__
  673.         elif isinstance(object, property):
  674.             return True
  675.         else:
  676.             raise ValueError('object must be a class or function')
  677.  
  678.     
  679.     def _find(self, tests, obj, name, module, source_lines, globs, seen):
  680.         '''
  681.         Find tests for the given object and any contained objects, and
  682.         add them to `tests`.
  683.         '''
  684.         if self._verbose:
  685.             print 'Finding tests in %s' % name
  686.         
  687.         if id(obj) in seen:
  688.             return None
  689.         
  690.         seen[id(obj)] = 1
  691.         test = self._get_test(obj, name, module, globs, source_lines)
  692.         if test is not None:
  693.             tests.append(test)
  694.         
  695.         if inspect.ismodule(obj) and self._recurse:
  696.             for valname, val in obj.__dict__.items():
  697.                 valname = '%s.%s' % (name, valname)
  698.                 if (inspect.isfunction(val) or inspect.isclass(val)) and self._from_module(module, val):
  699.                     self._find(tests, val, valname, module, source_lines, globs, seen)
  700.                     continue
  701.             
  702.         
  703.         if inspect.ismodule(obj) and self._recurse:
  704.             for valname, val in getattr(obj, '__test__', { }).items():
  705.                 if not isinstance(valname, basestring):
  706.                     raise ValueError('DocTestFinder.find: __test__ keys must be strings: %r' % (type(valname),))
  707.                 
  708.                 if not inspect.isfunction(val) and inspect.isclass(val) and inspect.ismethod(val) and inspect.ismodule(val) or isinstance(val, basestring):
  709.                     raise ValueError('DocTestFinder.find: __test__ values must be strings, functions, methods, classes, or modules: %r' % (type(val),))
  710.                 
  711.                 valname = '%s.__test__.%s' % (name, valname)
  712.                 self._find(tests, val, valname, module, source_lines, globs, seen)
  713.             
  714.         
  715.         if inspect.isclass(obj) and self._recurse:
  716.             for valname, val in obj.__dict__.items():
  717.                 if isinstance(val, staticmethod):
  718.                     val = getattr(obj, valname)
  719.                 
  720.                 if isinstance(val, classmethod):
  721.                     val = getattr(obj, valname).im_func
  722.                 
  723.                 if (inspect.isfunction(val) and inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val):
  724.                     valname = '%s.%s' % (name, valname)
  725.                     self._find(tests, val, valname, module, source_lines, globs, seen)
  726.                     continue
  727.             
  728.         
  729.  
  730.     
  731.     def _get_test(self, obj, name, module, globs, source_lines):
  732.         '''
  733.         Return a DocTest for the given object, if it defines a docstring;
  734.         otherwise, return None.
  735.         '''
  736.         if isinstance(obj, basestring):
  737.             docstring = obj
  738.         else:
  739.             
  740.             try:
  741.                 if obj.__doc__ is None:
  742.                     docstring = ''
  743.                 else:
  744.                     docstring = obj.__doc__
  745.                     if not isinstance(docstring, basestring):
  746.                         docstring = str(docstring)
  747.             except (TypeError, AttributeError):
  748.                 docstring = ''
  749.             
  750.  
  751.         lineno = self._find_lineno(obj, source_lines)
  752.         if self._exclude_empty and not docstring:
  753.             return None
  754.         
  755.         if module is None:
  756.             filename = None
  757.         else:
  758.             filename = getattr(module, '__file__', module.__name__)
  759.             if filename[-4:] in ('.pyc', '.pyo'):
  760.                 filename = filename[:-1]
  761.             
  762.         return self._parser.get_doctest(docstring, globs, name, filename, lineno)
  763.  
  764.     
  765.     def _find_lineno(self, obj, source_lines):
  766.         """
  767.         Return a line number of the given object's docstring.  Note:
  768.         this method assumes that the object has a docstring.
  769.         """
  770.         lineno = None
  771.         if inspect.ismodule(obj):
  772.             lineno = 0
  773.         
  774.         if inspect.isclass(obj):
  775.             if source_lines is None:
  776.                 return None
  777.             
  778.             pat = re.compile('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-'))
  779.             for i, line in enumerate(source_lines):
  780.                 if pat.match(line):
  781.                     lineno = i
  782.                     break
  783.                     continue
  784.             
  785.         
  786.         if inspect.ismethod(obj):
  787.             obj = obj.im_func
  788.         
  789.         if inspect.isfunction(obj):
  790.             obj = obj.func_code
  791.         
  792.         if inspect.istraceback(obj):
  793.             obj = obj.tb_frame
  794.         
  795.         if inspect.isframe(obj):
  796.             obj = obj.f_code
  797.         
  798.         if inspect.iscode(obj):
  799.             lineno = getattr(obj, 'co_firstlineno', None) - 1
  800.         
  801.         if lineno is not None:
  802.             if source_lines is None:
  803.                 return lineno + 1
  804.             
  805.             pat = re.compile('(^|.*:)\\s*\\w*("|\')')
  806.             for lineno in range(lineno, len(source_lines)):
  807.                 if pat.match(source_lines[lineno]):
  808.                     return lineno
  809.                     continue
  810.             
  811.         
  812.  
  813.  
  814.  
  815. class DocTestRunner:
  816.     """
  817.     A class used to run DocTest test cases, and accumulate statistics.
  818.     The `run` method is used to process a single DocTest case.  It
  819.     returns a tuple `(f, t)`, where `t` is the number of test cases
  820.     tried, and `f` is the number of test cases that failed.
  821.  
  822.         >>> tests = DocTestFinder().find(_TestClass)
  823.         >>> runner = DocTestRunner(verbose=False)
  824.         >>> tests.sort(key = lambda test: test.name)
  825.         >>> for test in tests:
  826.         ...     print test.name, '->', runner.run(test)
  827.         _TestClass -> (0, 2)
  828.         _TestClass.__init__ -> (0, 2)
  829.         _TestClass.get -> (0, 2)
  830.         _TestClass.square -> (0, 1)
  831.  
  832.     The `summarize` method prints a summary of all the test cases that
  833.     have been run by the runner, and returns an aggregated `(f, t)`
  834.     tuple:
  835.  
  836.         >>> runner.summarize(verbose=1)
  837.         4 items passed all tests:
  838.            2 tests in _TestClass
  839.            2 tests in _TestClass.__init__
  840.            2 tests in _TestClass.get
  841.            1 tests in _TestClass.square
  842.         7 tests in 4 items.
  843.         7 passed and 0 failed.
  844.         Test passed.
  845.         (0, 7)
  846.  
  847.     The aggregated number of tried examples and failed examples is
  848.     also available via the `tries` and `failures` attributes:
  849.  
  850.         >>> runner.tries
  851.         7
  852.         >>> runner.failures
  853.         0
  854.  
  855.     The comparison between expected outputs and actual outputs is done
  856.     by an `OutputChecker`.  This comparison may be customized with a
  857.     number of option flags; see the documentation for `testmod` for
  858.     more information.  If the option flags are insufficient, then the
  859.     comparison may also be customized by passing a subclass of
  860.     `OutputChecker` to the constructor.
  861.  
  862.     The test runner's display output can be controlled in two ways.
  863.     First, an output function (`out) can be passed to
  864.     `TestRunner.run`; this function will be called with strings that
  865.     should be displayed.  It defaults to `sys.stdout.write`.  If
  866.     capturing the output is not sufficient, then the display output
  867.     can be also customized by subclassing DocTestRunner, and
  868.     overriding the methods `report_start`, `report_success`,
  869.     `report_unexpected_exception`, and `report_failure`.
  870.     """
  871.     DIVIDER = '*' * 70
  872.     
  873.     def __init__(self, checker = None, verbose = None, optionflags = 0):
  874.         """
  875.         Create a new test runner.
  876.  
  877.         Optional keyword arg `checker` is the `OutputChecker` that
  878.         should be used to compare the expected outputs and actual
  879.         outputs of doctest examples.
  880.  
  881.         Optional keyword arg 'verbose' prints lots of stuff if true,
  882.         only failures if false; by default, it's true iff '-v' is in
  883.         sys.argv.
  884.  
  885.         Optional argument `optionflags` can be used to control how the
  886.         test runner compares expected output to actual output, and how
  887.         it displays failures.  See the documentation for `testmod` for
  888.         more information.
  889.         """
  890.         if not checker:
  891.             pass
  892.         self._checker = OutputChecker()
  893.         if verbose is None:
  894.             verbose = '-v' in sys.argv
  895.         
  896.         self._verbose = verbose
  897.         self.optionflags = optionflags
  898.         self.original_optionflags = optionflags
  899.         self.tries = 0
  900.         self.failures = 0
  901.         self._name2ft = { }
  902.         self._fakeout = _SpoofOut()
  903.  
  904.     
  905.     def report_start(self, out, test, example):
  906.         '''
  907.         Report that the test runner is about to process the given
  908.         example.  (Only displays a message if verbose=True)
  909.         '''
  910.         if self._verbose:
  911.             if example.want:
  912.                 out('Trying:\n' + _indent(example.source) + 'Expecting:\n' + _indent(example.want))
  913.             else:
  914.                 out('Trying:\n' + _indent(example.source) + 'Expecting nothing\n')
  915.         
  916.  
  917.     
  918.     def report_success(self, out, test, example, got):
  919.         '''
  920.         Report that the given example ran successfully.  (Only
  921.         displays a message if verbose=True)
  922.         '''
  923.         if self._verbose:
  924.             out('ok\n')
  925.         
  926.  
  927.     
  928.     def report_failure(self, out, test, example, got):
  929.         '''
  930.         Report that the given example failed.
  931.         '''
  932.         out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags))
  933.  
  934.     
  935.     def report_unexpected_exception(self, out, test, example, exc_info):
  936.         '''
  937.         Report that the given example raised an unexpected exception.
  938.         '''
  939.         out(self._failure_header(test, example) + 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
  940.  
  941.     
  942.     def _failure_header(self, test, example):
  943.         out = [
  944.             self.DIVIDER]
  945.         if test.filename:
  946.             if test.lineno is not None and example.lineno is not None:
  947.                 lineno = test.lineno + example.lineno + 1
  948.             else:
  949.                 lineno = '?'
  950.             out.append('File "%s", line %s, in %s' % (test.filename, lineno, test.name))
  951.         else:
  952.             out.append('Line %s, in %s' % (example.lineno + 1, test.name))
  953.         out.append('Failed example:')
  954.         source = example.source
  955.         out.append(_indent(source))
  956.         return '\n'.join(out)
  957.  
  958.     
  959.     def __run(self, test, compileflags, out):
  960.         '''
  961.         Run the examples in `test`.  Write the outcome of each example
  962.         with one of the `DocTestRunner.report_*` methods, using the
  963.         writer function `out`.  `compileflags` is the set of compiler
  964.         flags that should be used to execute examples.  Return a tuple
  965.         `(f, t)`, where `t` is the number of examples tried, and `f`
  966.         is the number of examples that failed.  The examples are run
  967.         in the namespace `test.globs`.
  968.         '''
  969.         failures = tries = 0
  970.         original_optionflags = self.optionflags
  971.         (SUCCESS, FAILURE, BOOM) = range(3)
  972.         check = self._checker.check_output
  973.         for examplenum, example in enumerate(test.examples):
  974.             if self.optionflags & REPORT_ONLY_FIRST_FAILURE:
  975.                 pass
  976.             quiet = failures > 0
  977.             self.optionflags = original_optionflags
  978.             if example.options:
  979.                 for optionflag, val in example.options.items():
  980.                     if val:
  981.                         self.optionflags |= optionflag
  982.                         continue
  983.                     self
  984.                     self.optionflags &= ~optionflag
  985.                 
  986.             
  987.             if self.optionflags & SKIP:
  988.                 continue
  989.             
  990.             tries += 1
  991.             if not quiet:
  992.                 self.report_start(out, test, example)
  993.             
  994.             filename = '<doctest %s[%d]>' % (test.name, examplenum)
  995.             
  996.             try:
  997.                 exec compile(example.source, filename, 'single', compileflags, 1) in test.globs
  998.                 self.debugger.set_continue()
  999.                 exception = None
  1000.             except KeyboardInterrupt:
  1001.                 raise 
  1002.             except:
  1003.                 exception = sys.exc_info()
  1004.                 self.debugger.set_continue()
  1005.  
  1006.             got = self._fakeout.getvalue()
  1007.             self._fakeout.truncate(0)
  1008.             outcome = FAILURE
  1009.             if exception is None:
  1010.                 if check(example.want, got, self.optionflags):
  1011.                     outcome = SUCCESS
  1012.                 
  1013.             else:
  1014.                 exc_info = sys.exc_info()
  1015.                 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
  1016.                 if not quiet:
  1017.                     got += _exception_traceback(exc_info)
  1018.                 
  1019.                 if example.exc_msg is None:
  1020.                     outcome = BOOM
  1021.                 elif check(example.exc_msg, exc_msg, self.optionflags):
  1022.                     outcome = SUCCESS
  1023.                 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
  1024.                     m1 = re.match('[^:]*:', example.exc_msg)
  1025.                     m2 = re.match('[^:]*:', exc_msg)
  1026.                     if m1 and m2 and check(m1.group(0), m2.group(0), self.optionflags):
  1027.                         outcome = SUCCESS
  1028.                     
  1029.                 
  1030.             if outcome is SUCCESS:
  1031.                 if not quiet:
  1032.                     self.report_success(out, test, example, got)
  1033.                 
  1034.             quiet
  1035.             if outcome is FAILURE:
  1036.                 if not quiet:
  1037.                     self.report_failure(out, test, example, got)
  1038.                 
  1039.                 failures += 1
  1040.                 continue
  1041.             if outcome is BOOM:
  1042.                 if not quiet:
  1043.                     self.report_unexpected_exception(out, test, example, exc_info)
  1044.                 
  1045.                 failures += 1
  1046.                 continue
  1047.             if not False:
  1048.                 raise AssertionError, ('unknown outcome', outcome)
  1049.         
  1050.         self.optionflags = original_optionflags
  1051.         self._DocTestRunner__record_outcome(test, failures, tries)
  1052.         return (failures, tries)
  1053.  
  1054.     
  1055.     def __record_outcome(self, test, f, t):
  1056.         '''
  1057.         Record the fact that the given DocTest (`test`) generated `f`
  1058.         failures out of `t` tried examples.
  1059.         '''
  1060.         (f2, t2) = self._name2ft.get(test.name, (0, 0))
  1061.         self._name2ft[test.name] = (f + f2, t + t2)
  1062.         self.failures += f
  1063.         self.tries += t
  1064.  
  1065.     __LINECACHE_FILENAME_RE = re.compile('<doctest (?P<name>[\\w\\.]+)\\[(?P<examplenum>\\d+)\\]>$')
  1066.     
  1067.     def __patched_linecache_getlines(self, filename, module_globals = None):
  1068.         m = self._DocTestRunner__LINECACHE_FILENAME_RE.match(filename)
  1069.         if m and m.group('name') == self.test.name:
  1070.             example = self.test.examples[int(m.group('examplenum'))]
  1071.             return example.source.splitlines(True)
  1072.         else:
  1073.             return self.save_linecache_getlines(filename, module_globals)
  1074.  
  1075.     
  1076.     def run(self, test, compileflags = None, out = None, clear_globs = True):
  1077.         '''
  1078.         Run the examples in `test`, and display the results using the
  1079.         writer function `out`.
  1080.  
  1081.         The examples are run in the namespace `test.globs`.  If
  1082.         `clear_globs` is true (the default), then this namespace will
  1083.         be cleared after the test runs, to help with garbage
  1084.         collection.  If you would like to examine the namespace after
  1085.         the test completes, then use `clear_globs=False`.
  1086.  
  1087.         `compileflags` gives the set of flags that should be used by
  1088.         the Python compiler when running the examples.  If not
  1089.         specified, then it will default to the set of future-import
  1090.         flags that apply to `globs`.
  1091.  
  1092.         The output of each example is checked using
  1093.         `DocTestRunner.check_output`, and the results are formatted by
  1094.         the `DocTestRunner.report_*` methods.
  1095.         '''
  1096.         self.test = test
  1097.         if compileflags is None:
  1098.             compileflags = _extract_future_flags(test.globs)
  1099.         
  1100.         save_stdout = sys.stdout
  1101.         if out is None:
  1102.             out = save_stdout.write
  1103.         
  1104.         sys.stdout = self._fakeout
  1105.         save_set_trace = pdb.set_trace
  1106.         self.debugger = _OutputRedirectingPdb(save_stdout)
  1107.         self.debugger.reset()
  1108.         pdb.set_trace = self.debugger.set_trace
  1109.         self.save_linecache_getlines = linecache.getlines
  1110.         linecache.getlines = self._DocTestRunner__patched_linecache_getlines
  1111.         
  1112.         try:
  1113.             return self._DocTestRunner__run(test, compileflags, out)
  1114.         finally:
  1115.             sys.stdout = save_stdout
  1116.             pdb.set_trace = save_set_trace
  1117.             linecache.getlines = self.save_linecache_getlines
  1118.             if clear_globs:
  1119.                 test.globs.clear()
  1120.             
  1121.  
  1122.  
  1123.     
  1124.     def summarize(self, verbose = None):
  1125.         """
  1126.         Print a summary of all the test cases that have been run by
  1127.         this DocTestRunner, and return a tuple `(f, t)`, where `f` is
  1128.         the total number of failed examples, and `t` is the total
  1129.         number of tried examples.
  1130.  
  1131.         The optional `verbose` argument controls how detailed the
  1132.         summary is.  If the verbosity is not specified, then the
  1133.         DocTestRunner's verbosity is used.
  1134.         """
  1135.         if verbose is None:
  1136.             verbose = self._verbose
  1137.         
  1138.         notests = []
  1139.         passed = []
  1140.         failed = []
  1141.         totalt = totalf = 0
  1142.         for x in self._name2ft.items():
  1143.             (f, t) = (name,)
  1144.             if not f <= t:
  1145.                 raise AssertionError
  1146.             x
  1147.             totalt += t
  1148.             totalf += f
  1149.             if t == 0:
  1150.                 notests.append(name)
  1151.                 continue
  1152.             if f == 0:
  1153.                 passed.append((name, t))
  1154.                 continue
  1155.             failed.append(x)
  1156.         
  1157.         if verbose:
  1158.             if notests:
  1159.                 print len(notests), 'items had no tests:'
  1160.                 notests.sort()
  1161.                 for thing in notests:
  1162.                     print '   ', thing
  1163.                 
  1164.             
  1165.             if passed:
  1166.                 print len(passed), 'items passed all tests:'
  1167.                 passed.sort()
  1168.                 for thing, count in passed:
  1169.                     print ' %3d tests in %s' % (count, thing)
  1170.                 
  1171.             
  1172.         
  1173.         if failed:
  1174.             print self.DIVIDER
  1175.             print len(failed), 'items had failures:'
  1176.             failed.sort()
  1177.             for f, t in failed:
  1178.                 print ' %3d of %3d in %s' % (f, t, thing)
  1179.             
  1180.         
  1181.         if verbose:
  1182.             print totalt, 'tests in', len(self._name2ft), 'items.'
  1183.             print totalt - totalf, 'passed and', totalf, 'failed.'
  1184.         
  1185.         if totalf:
  1186.             print '***Test Failed***', totalf, 'failures.'
  1187.         elif verbose:
  1188.             print 'Test passed.'
  1189.         
  1190.         return (totalf, totalt)
  1191.  
  1192.     
  1193.     def merge(self, other):
  1194.         d = self._name2ft
  1195.         for f, t in other._name2ft.items():
  1196.             d[name] = (f, t)
  1197.         
  1198.  
  1199.  
  1200.  
  1201. class OutputChecker:
  1202.     '''
  1203.     A class used to check the whether the actual output from a doctest
  1204.     example matches the expected output.  `OutputChecker` defines two
  1205.     methods: `check_output`, which compares a given pair of outputs,
  1206.     and returns true if they match; and `output_difference`, which
  1207.     returns a string describing the differences between two outputs.
  1208.     '''
  1209.     
  1210.     def check_output(self, want, got, optionflags):
  1211.         '''
  1212.         Return True iff the actual output from an example (`got`)
  1213.         matches the expected output (`want`).  These strings are
  1214.         always considered to match if they are identical; but
  1215.         depending on what option flags the test runner is using,
  1216.         several non-exact match types are also possible.  See the
  1217.         documentation for `TestRunner` for more information about
  1218.         option flags.
  1219.         '''
  1220.         if got == want:
  1221.             return True
  1222.         
  1223.         if not optionflags & DONT_ACCEPT_TRUE_FOR_1:
  1224.             if (got, want) == ('True\n', '1\n'):
  1225.                 return True
  1226.             
  1227.             if (got, want) == ('False\n', '0\n'):
  1228.                 return True
  1229.             
  1230.         
  1231.         if not optionflags & DONT_ACCEPT_BLANKLINE:
  1232.             want = re.sub('(?m)^%s\\s*?$' % re.escape(BLANKLINE_MARKER), '', want)
  1233.             got = re.sub('(?m)^\\s*?$', '', got)
  1234.             if got == want:
  1235.                 return True
  1236.             
  1237.         
  1238.         if optionflags & NORMALIZE_WHITESPACE:
  1239.             got = ' '.join(got.split())
  1240.             want = ' '.join(want.split())
  1241.             if got == want:
  1242.                 return True
  1243.             
  1244.         
  1245.         if optionflags & ELLIPSIS:
  1246.             if _ellipsis_match(want, got):
  1247.                 return True
  1248.             
  1249.         
  1250.         return False
  1251.  
  1252.     
  1253.     def _do_a_fancy_diff(self, want, got, optionflags):
  1254.         if not optionflags & (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF):
  1255.             return False
  1256.         
  1257.         if optionflags & REPORT_NDIFF:
  1258.             return True
  1259.         
  1260.         if want.count('\n') > 2:
  1261.             pass
  1262.         return got.count('\n') > 2
  1263.  
  1264.     
  1265.     def output_difference(self, example, got, optionflags):
  1266.         '''
  1267.         Return a string describing the differences between the
  1268.         expected output for a given example (`example`) and the actual
  1269.         output (`got`).  `optionflags` is the set of option flags used
  1270.         to compare `want` and `got`.
  1271.         '''
  1272.         want = example.want
  1273.         if not optionflags & DONT_ACCEPT_BLANKLINE:
  1274.             got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
  1275.         
  1276.         if want and got:
  1277.             return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
  1278.         elif want:
  1279.             return 'Expected:\n%sGot nothing\n' % _indent(want)
  1280.         elif got:
  1281.             return 'Expected nothing\nGot:\n%s' % _indent(got)
  1282.         else:
  1283.             return 'Expected nothing\nGot nothing\n'
  1284.  
  1285.  
  1286.  
  1287. class DocTestFailure(Exception):
  1288.     '''A DocTest example has failed in debugging mode.
  1289.  
  1290.     The exception instance has variables:
  1291.  
  1292.     - test: the DocTest object being run
  1293.  
  1294.     - example: the Example object that failed
  1295.  
  1296.     - got: the actual output
  1297.     '''
  1298.     
  1299.     def __init__(self, test, example, got):
  1300.         self.test = test
  1301.         self.example = example
  1302.         self.got = got
  1303.  
  1304.     
  1305.     def __str__(self):
  1306.         return str(self.test)
  1307.  
  1308.  
  1309.  
  1310. class UnexpectedException(Exception):
  1311.     '''A DocTest example has encountered an unexpected exception
  1312.  
  1313.     The exception instance has variables:
  1314.  
  1315.     - test: the DocTest object being run
  1316.  
  1317.     - example: the Example object that failed
  1318.  
  1319.     - exc_info: the exception info
  1320.     '''
  1321.     
  1322.     def __init__(self, test, example, exc_info):
  1323.         self.test = test
  1324.         self.example = example
  1325.         self.exc_info = exc_info
  1326.  
  1327.     
  1328.     def __str__(self):
  1329.         return str(self.test)
  1330.  
  1331.  
  1332.  
  1333. class DebugRunner(DocTestRunner):
  1334.     """Run doc tests but raise an exception as soon as there is a failure.
  1335.  
  1336.        If an unexpected exception occurs, an UnexpectedException is raised.
  1337.        It contains the test, the example, and the original exception:
  1338.  
  1339.          >>> runner = DebugRunner(verbose=False)
  1340.          >>> test = DocTestParser().get_doctest('>>> raise KeyError\\n42',
  1341.          ...                                    {}, 'foo', 'foo.py', 0)
  1342.          >>> try:
  1343.          ...     runner.run(test)
  1344.          ... except UnexpectedException, failure:
  1345.          ...     pass
  1346.  
  1347.          >>> failure.test is test
  1348.          True
  1349.  
  1350.          >>> failure.example.want
  1351.          '42\\n'
  1352.  
  1353.          >>> exc_info = failure.exc_info
  1354.          >>> raise exc_info[0], exc_info[1], exc_info[2]
  1355.          Traceback (most recent call last):
  1356.          ...
  1357.          KeyError
  1358.  
  1359.        We wrap the original exception to give the calling application
  1360.        access to the test and example information.
  1361.  
  1362.        If the output doesn't match, then a DocTestFailure is raised:
  1363.  
  1364.          >>> test = DocTestParser().get_doctest('''
  1365.          ...      >>> x = 1
  1366.          ...      >>> x
  1367.          ...      2
  1368.          ...      ''', {}, 'foo', 'foo.py', 0)
  1369.  
  1370.          >>> try:
  1371.          ...    runner.run(test)
  1372.          ... except DocTestFailure, failure:
  1373.          ...    pass
  1374.  
  1375.        DocTestFailure objects provide access to the test:
  1376.  
  1377.          >>> failure.test is test
  1378.          True
  1379.  
  1380.        As well as to the example:
  1381.  
  1382.          >>> failure.example.want
  1383.          '2\\n'
  1384.  
  1385.        and the actual output:
  1386.  
  1387.          >>> failure.got
  1388.          '1\\n'
  1389.  
  1390.        If a failure or error occurs, the globals are left intact:
  1391.  
  1392.          >>> del test.globs['__builtins__']
  1393.          >>> test.globs
  1394.          {'x': 1}
  1395.  
  1396.          >>> test = DocTestParser().get_doctest('''
  1397.          ...      >>> x = 2
  1398.          ...      >>> raise KeyError
  1399.          ...      ''', {}, 'foo', 'foo.py', 0)
  1400.  
  1401.          >>> runner.run(test)
  1402.          Traceback (most recent call last):
  1403.          ...
  1404.          UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
  1405.  
  1406.          >>> del test.globs['__builtins__']
  1407.          >>> test.globs
  1408.          {'x': 2}
  1409.  
  1410.        But the globals are cleared if there is no error:
  1411.  
  1412.          >>> test = DocTestParser().get_doctest('''
  1413.          ...      >>> x = 2
  1414.          ...      ''', {}, 'foo', 'foo.py', 0)
  1415.  
  1416.          >>> runner.run(test)
  1417.          (0, 1)
  1418.  
  1419.          >>> test.globs
  1420.          {}
  1421.  
  1422.        """
  1423.     
  1424.     def run(self, test, compileflags = None, out = None, clear_globs = True):
  1425.         r = DocTestRunner.run(self, test, compileflags, out, False)
  1426.         if clear_globs:
  1427.             test.globs.clear()
  1428.         
  1429.         return r
  1430.  
  1431.     
  1432.     def report_unexpected_exception(self, out, test, example, exc_info):
  1433.         raise UnexpectedException(test, example, exc_info)
  1434.  
  1435.     
  1436.     def report_failure(self, out, test, example, got):
  1437.         raise DocTestFailure(test, example, got)
  1438.  
  1439.  
  1440. master = None
  1441.  
  1442. def testmod(m = None, name = None, globs = None, verbose = None, report = True, optionflags = 0, extraglobs = None, raise_on_error = False, exclude_empty = False):
  1443.     '''m=None, name=None, globs=None, verbose=None, report=True,
  1444.        optionflags=0, extraglobs=None, raise_on_error=False,
  1445.        exclude_empty=False
  1446.  
  1447.     Test examples in docstrings in functions and classes reachable
  1448.     from module m (or the current module if m is not supplied), starting
  1449.     with m.__doc__.
  1450.  
  1451.     Also test examples reachable from dict m.__test__ if it exists and is
  1452.     not None.  m.__test__ maps names to functions, classes and strings;
  1453.     function and class docstrings are tested even if the name is private;
  1454.     strings are tested directly, as if they were docstrings.
  1455.  
  1456.     Return (#failures, #tests).
  1457.  
  1458.     See doctest.__doc__ for an overview.
  1459.  
  1460.     Optional keyword arg "name" gives the name of the module; by default
  1461.     use m.__name__.
  1462.  
  1463.     Optional keyword arg "globs" gives a dict to be used as the globals
  1464.     when executing examples; by default, use m.__dict__.  A copy of this
  1465.     dict is actually used for each docstring, so that each docstring\'s
  1466.     examples start with a clean slate.
  1467.  
  1468.     Optional keyword arg "extraglobs" gives a dictionary that should be
  1469.     merged into the globals that are used to execute examples.  By
  1470.     default, no extra globals are used.  This is new in 2.4.
  1471.  
  1472.     Optional keyword arg "verbose" prints lots of stuff if true, prints
  1473.     only failures if false; by default, it\'s true iff "-v" is in sys.argv.
  1474.  
  1475.     Optional keyword arg "report" prints a summary at the end when true,
  1476.     else prints nothing at the end.  In verbose mode, the summary is
  1477.     detailed, else very brief (in fact, empty if all tests passed).
  1478.  
  1479.     Optional keyword arg "optionflags" or\'s together module constants,
  1480.     and defaults to 0.  This is new in 2.3.  Possible values (see the
  1481.     docs for details):
  1482.  
  1483.         DONT_ACCEPT_TRUE_FOR_1
  1484.         DONT_ACCEPT_BLANKLINE
  1485.         NORMALIZE_WHITESPACE
  1486.         ELLIPSIS
  1487.         SKIP
  1488.         IGNORE_EXCEPTION_DETAIL
  1489.         REPORT_UDIFF
  1490.         REPORT_CDIFF
  1491.         REPORT_NDIFF
  1492.         REPORT_ONLY_FIRST_FAILURE
  1493.  
  1494.     Optional keyword arg "raise_on_error" raises an exception on the
  1495.     first unexpected exception or failure. This allows failures to be
  1496.     post-mortem debugged.
  1497.  
  1498.     Advanced tomfoolery:  testmod runs methods of a local instance of
  1499.     class doctest.Tester, then merges the results into (or creates)
  1500.     global Tester instance doctest.master.  Methods of doctest.master
  1501.     can be called directly too, if you want to do something unusual.
  1502.     Passing report=0 to testmod is especially useful then, to delay
  1503.     displaying a summary.  Invoke doctest.master.summarize(verbose)
  1504.     when you\'re done fiddling.
  1505.     '''
  1506.     global master
  1507.     if m is None:
  1508.         m = sys.modules.get('__main__')
  1509.     
  1510.     if not inspect.ismodule(m):
  1511.         raise TypeError('testmod: module required; %r' % (m,))
  1512.     
  1513.     if name is None:
  1514.         name = m.__name__
  1515.     
  1516.     finder = DocTestFinder(exclude_empty = exclude_empty)
  1517.     if raise_on_error:
  1518.         runner = DebugRunner(verbose = verbose, optionflags = optionflags)
  1519.     else:
  1520.         runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1521.     for test in finder.find(m, name, globs = globs, extraglobs = extraglobs):
  1522.         runner.run(test)
  1523.     
  1524.     if report:
  1525.         runner.summarize()
  1526.     
  1527.     if master is None:
  1528.         master = runner
  1529.     else:
  1530.         master.merge(runner)
  1531.     return (runner.failures, runner.tries)
  1532.  
  1533.  
  1534. def testfile(filename, module_relative = True, name = None, package = None, globs = None, verbose = None, report = True, optionflags = 0, extraglobs = None, raise_on_error = False, parser = DocTestParser(), encoding = None):
  1535.     '''
  1536.     Test examples in the given file.  Return (#failures, #tests).
  1537.  
  1538.     Optional keyword arg "module_relative" specifies how filenames
  1539.     should be interpreted:
  1540.  
  1541.       - If "module_relative" is True (the default), then "filename"
  1542.          specifies a module-relative path.  By default, this path is
  1543.          relative to the calling module\'s directory; but if the
  1544.          "package" argument is specified, then it is relative to that
  1545.          package.  To ensure os-independence, "filename" should use
  1546.          "/" characters to separate path segments, and should not
  1547.          be an absolute path (i.e., it may not begin with "/").
  1548.  
  1549.       - If "module_relative" is False, then "filename" specifies an
  1550.         os-specific path.  The path may be absolute or relative (to
  1551.         the current working directory).
  1552.  
  1553.     Optional keyword arg "name" gives the name of the test; by default
  1554.     use the file\'s basename.
  1555.  
  1556.     Optional keyword argument "package" is a Python package or the
  1557.     name of a Python package whose directory should be used as the
  1558.     base directory for a module relative filename.  If no package is
  1559.     specified, then the calling module\'s directory is used as the base
  1560.     directory for module relative filenames.  It is an error to
  1561.     specify "package" if "module_relative" is False.
  1562.  
  1563.     Optional keyword arg "globs" gives a dict to be used as the globals
  1564.     when executing examples; by default, use {}.  A copy of this dict
  1565.     is actually used for each docstring, so that each docstring\'s
  1566.     examples start with a clean slate.
  1567.  
  1568.     Optional keyword arg "extraglobs" gives a dictionary that should be
  1569.     merged into the globals that are used to execute examples.  By
  1570.     default, no extra globals are used.
  1571.  
  1572.     Optional keyword arg "verbose" prints lots of stuff if true, prints
  1573.     only failures if false; by default, it\'s true iff "-v" is in sys.argv.
  1574.  
  1575.     Optional keyword arg "report" prints a summary at the end when true,
  1576.     else prints nothing at the end.  In verbose mode, the summary is
  1577.     detailed, else very brief (in fact, empty if all tests passed).
  1578.  
  1579.     Optional keyword arg "optionflags" or\'s together module constants,
  1580.     and defaults to 0.  Possible values (see the docs for details):
  1581.  
  1582.         DONT_ACCEPT_TRUE_FOR_1
  1583.         DONT_ACCEPT_BLANKLINE
  1584.         NORMALIZE_WHITESPACE
  1585.         ELLIPSIS
  1586.         SKIP
  1587.         IGNORE_EXCEPTION_DETAIL
  1588.         REPORT_UDIFF
  1589.         REPORT_CDIFF
  1590.         REPORT_NDIFF
  1591.         REPORT_ONLY_FIRST_FAILURE
  1592.  
  1593.     Optional keyword arg "raise_on_error" raises an exception on the
  1594.     first unexpected exception or failure. This allows failures to be
  1595.     post-mortem debugged.
  1596.  
  1597.     Optional keyword arg "parser" specifies a DocTestParser (or
  1598.     subclass) that should be used to extract tests from the files.
  1599.  
  1600.     Optional keyword arg "encoding" specifies an encoding that should
  1601.     be used to convert the file to unicode.
  1602.  
  1603.     Advanced tomfoolery:  testmod runs methods of a local instance of
  1604.     class doctest.Tester, then merges the results into (or creates)
  1605.     global Tester instance doctest.master.  Methods of doctest.master
  1606.     can be called directly too, if you want to do something unusual.
  1607.     Passing report=0 to testmod is especially useful then, to delay
  1608.     displaying a summary.  Invoke doctest.master.summarize(verbose)
  1609.     when you\'re done fiddling.
  1610.     '''
  1611.     global master
  1612.     if package and not module_relative:
  1613.         raise ValueError('Package may only be specified for module-relative paths.')
  1614.     
  1615.     (text, filename) = _load_testfile(filename, package, module_relative)
  1616.     if name is None:
  1617.         name = os.path.basename(filename)
  1618.     
  1619.     if globs is None:
  1620.         globs = { }
  1621.     else:
  1622.         globs = globs.copy()
  1623.     if extraglobs is not None:
  1624.         globs.update(extraglobs)
  1625.     
  1626.     if raise_on_error:
  1627.         runner = DebugRunner(verbose = verbose, optionflags = optionflags)
  1628.     else:
  1629.         runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1630.     if encoding is not None:
  1631.         text = text.decode(encoding)
  1632.     
  1633.     test = parser.get_doctest(text, globs, name, filename, 0)
  1634.     runner.run(test)
  1635.     if report:
  1636.         runner.summarize()
  1637.     
  1638.     if master is None:
  1639.         master = runner
  1640.     else:
  1641.         master.merge(runner)
  1642.     return (runner.failures, runner.tries)
  1643.  
  1644.  
  1645. def run_docstring_examples(f, globs, verbose = False, name = 'NoName', compileflags = None, optionflags = 0):
  1646.     """
  1647.     Test examples in the given object's docstring (`f`), using `globs`
  1648.     as globals.  Optional argument `name` is used in failure messages.
  1649.     If the optional argument `verbose` is true, then generate output
  1650.     even if there are no failures.
  1651.  
  1652.     `compileflags` gives the set of flags that should be used by the
  1653.     Python compiler when running the examples.  If not specified, then
  1654.     it will default to the set of future-import flags that apply to
  1655.     `globs`.
  1656.  
  1657.     Optional keyword arg `optionflags` specifies options for the
  1658.     testing and output.  See the documentation for `testmod` for more
  1659.     information.
  1660.     """
  1661.     finder = DocTestFinder(verbose = verbose, recurse = False)
  1662.     runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1663.     for test in finder.find(f, name, globs = globs):
  1664.         runner.run(test, compileflags = compileflags)
  1665.     
  1666.  
  1667.  
  1668. class Tester:
  1669.     
  1670.     def __init__(self, mod = None, globs = None, verbose = None, optionflags = 0):
  1671.         warnings.warn('class Tester is deprecated; use class doctest.DocTestRunner instead', DeprecationWarning, stacklevel = 2)
  1672.         if mod is None and globs is None:
  1673.             raise TypeError('Tester.__init__: must specify mod or globs')
  1674.         
  1675.         if mod is not None and not inspect.ismodule(mod):
  1676.             raise TypeError('Tester.__init__: mod must be a module; %r' % (mod,))
  1677.         
  1678.         if globs is None:
  1679.             globs = mod.__dict__
  1680.         
  1681.         self.globs = globs
  1682.         self.verbose = verbose
  1683.         self.optionflags = optionflags
  1684.         self.testfinder = DocTestFinder()
  1685.         self.testrunner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1686.  
  1687.     
  1688.     def runstring(self, s, name):
  1689.         test = DocTestParser().get_doctest(s, self.globs, name, None, None)
  1690.         if self.verbose:
  1691.             print 'Running string', name
  1692.         
  1693.         (f, t) = self.testrunner.run(test)
  1694.         if self.verbose:
  1695.             print f, 'of', t, 'examples failed in string', name
  1696.         
  1697.         return (f, t)
  1698.  
  1699.     
  1700.     def rundoc(self, object, name = None, module = None):
  1701.         f = t = 0
  1702.         tests = self.testfinder.find(object, name, module = module, globs = self.globs)
  1703.         for test in tests:
  1704.             (f2, t2) = self.testrunner.run(test)
  1705.             f = f + f2
  1706.             t = t + t2
  1707.         
  1708.         return (f, t)
  1709.  
  1710.     
  1711.     def rundict(self, d, name, module = None):
  1712.         import new
  1713.         m = new.module(name)
  1714.         m.__dict__.update(d)
  1715.         if module is None:
  1716.             module = False
  1717.         
  1718.         return self.rundoc(m, name, module)
  1719.  
  1720.     
  1721.     def run__test__(self, d, name):
  1722.         import new
  1723.         m = new.module(name)
  1724.         m.__test__ = d
  1725.         return self.rundoc(m, name)
  1726.  
  1727.     
  1728.     def summarize(self, verbose = None):
  1729.         return self.testrunner.summarize(verbose)
  1730.  
  1731.     
  1732.     def merge(self, other):
  1733.         self.testrunner.merge(other.testrunner)
  1734.  
  1735.  
  1736. _unittest_reportflags = 0
  1737.  
  1738. def set_unittest_reportflags(flags):
  1739.     """Sets the unittest option flags.
  1740.  
  1741.     The old flag is returned so that a runner could restore the old
  1742.     value if it wished to:
  1743.  
  1744.       >>> import doctest
  1745.       >>> old = doctest._unittest_reportflags
  1746.       >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
  1747.       ...                          REPORT_ONLY_FIRST_FAILURE) == old
  1748.       True
  1749.  
  1750.       >>> doctest._unittest_reportflags == (REPORT_NDIFF |
  1751.       ...                                   REPORT_ONLY_FIRST_FAILURE)
  1752.       True
  1753.  
  1754.     Only reporting flags can be set:
  1755.  
  1756.       >>> doctest.set_unittest_reportflags(ELLIPSIS)
  1757.       Traceback (most recent call last):
  1758.       ...
  1759.       ValueError: ('Only reporting flags allowed', 8)
  1760.  
  1761.       >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
  1762.       ...                                   REPORT_ONLY_FIRST_FAILURE)
  1763.       True
  1764.     """
  1765.     global _unittest_reportflags
  1766.     if flags & REPORTING_FLAGS != flags:
  1767.         raise ValueError('Only reporting flags allowed', flags)
  1768.     
  1769.     old = _unittest_reportflags
  1770.     _unittest_reportflags = flags
  1771.     return old
  1772.  
  1773.  
  1774. class DocTestCase(unittest.TestCase):
  1775.     
  1776.     def __init__(self, test, optionflags = 0, setUp = None, tearDown = None, checker = None):
  1777.         unittest.TestCase.__init__(self)
  1778.         self._dt_optionflags = optionflags
  1779.         self._dt_checker = checker
  1780.         self._dt_test = test
  1781.         self._dt_setUp = setUp
  1782.         self._dt_tearDown = tearDown
  1783.  
  1784.     
  1785.     def setUp(self):
  1786.         test = self._dt_test
  1787.         if self._dt_setUp is not None:
  1788.             self._dt_setUp(test)
  1789.         
  1790.  
  1791.     
  1792.     def tearDown(self):
  1793.         test = self._dt_test
  1794.         if self._dt_tearDown is not None:
  1795.             self._dt_tearDown(test)
  1796.         
  1797.         test.globs.clear()
  1798.  
  1799.     
  1800.     def runTest(self):
  1801.         test = self._dt_test
  1802.         old = sys.stdout
  1803.         new = StringIO()
  1804.         optionflags = self._dt_optionflags
  1805.         if not optionflags & REPORTING_FLAGS:
  1806.             optionflags |= _unittest_reportflags
  1807.         
  1808.         runner = DocTestRunner(optionflags = optionflags, checker = self._dt_checker, verbose = False)
  1809.         
  1810.         try:
  1811.             runner.DIVIDER = '-' * 70
  1812.             (failures, tries) = runner.run(test, out = new.write, clear_globs = False)
  1813.         finally:
  1814.             sys.stdout = old
  1815.  
  1816.         if failures:
  1817.             raise self.failureException(self.format_failure(new.getvalue()))
  1818.         
  1819.  
  1820.     
  1821.     def format_failure(self, err):
  1822.         test = self._dt_test
  1823.         if test.lineno is None:
  1824.             lineno = 'unknown line number'
  1825.         else:
  1826.             lineno = '%s' % test.lineno
  1827.         lname = '.'.join(test.name.split('.')[-1:])
  1828.         return 'Failed doctest test for %s\n  File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err)
  1829.  
  1830.     
  1831.     def debug(self):
  1832.         """Run the test case without results and without catching exceptions
  1833.  
  1834.            The unit test framework includes a debug method on test cases
  1835.            and test suites to support post-mortem debugging.  The test code
  1836.            is run in such a way that errors are not caught.  This way a
  1837.            caller can catch the errors and initiate post-mortem debugging.
  1838.  
  1839.            The DocTestCase provides a debug method that raises
  1840.            UnexpectedException errors if there is an unexepcted
  1841.            exception:
  1842.  
  1843.              >>> test = DocTestParser().get_doctest('>>> raise KeyError\\n42',
  1844.              ...                {}, 'foo', 'foo.py', 0)
  1845.              >>> case = DocTestCase(test)
  1846.              >>> try:
  1847.              ...     case.debug()
  1848.              ... except UnexpectedException, failure:
  1849.              ...     pass
  1850.  
  1851.            The UnexpectedException contains the test, the example, and
  1852.            the original exception:
  1853.  
  1854.              >>> failure.test is test
  1855.              True
  1856.  
  1857.              >>> failure.example.want
  1858.              '42\\n'
  1859.  
  1860.              >>> exc_info = failure.exc_info
  1861.              >>> raise exc_info[0], exc_info[1], exc_info[2]
  1862.              Traceback (most recent call last):
  1863.              ...
  1864.              KeyError
  1865.  
  1866.            If the output doesn't match, then a DocTestFailure is raised:
  1867.  
  1868.              >>> test = DocTestParser().get_doctest('''
  1869.              ...      >>> x = 1
  1870.              ...      >>> x
  1871.              ...      2
  1872.              ...      ''', {}, 'foo', 'foo.py', 0)
  1873.              >>> case = DocTestCase(test)
  1874.  
  1875.              >>> try:
  1876.              ...    case.debug()
  1877.              ... except DocTestFailure, failure:
  1878.              ...    pass
  1879.  
  1880.            DocTestFailure objects provide access to the test:
  1881.  
  1882.              >>> failure.test is test
  1883.              True
  1884.  
  1885.            As well as to the example:
  1886.  
  1887.              >>> failure.example.want
  1888.              '2\\n'
  1889.  
  1890.            and the actual output:
  1891.  
  1892.              >>> failure.got
  1893.              '1\\n'
  1894.  
  1895.            """
  1896.         self.setUp()
  1897.         runner = DebugRunner(optionflags = self._dt_optionflags, checker = self._dt_checker, verbose = False)
  1898.         runner.run(self._dt_test)
  1899.         self.tearDown()
  1900.  
  1901.     
  1902.     def id(self):
  1903.         return self._dt_test.name
  1904.  
  1905.     
  1906.     def __repr__(self):
  1907.         name = self._dt_test.name.split('.')
  1908.         return '%s (%s)' % (name[-1], '.'.join(name[:-1]))
  1909.  
  1910.     __str__ = __repr__
  1911.     
  1912.     def shortDescription(self):
  1913.         return 'Doctest: ' + self._dt_test.name
  1914.  
  1915.  
  1916.  
  1917. def DocTestSuite(module = None, globs = None, extraglobs = None, test_finder = None, **options):
  1918.     '''
  1919.     Convert doctest tests for a module to a unittest test suite.
  1920.  
  1921.     This converts each documentation string in a module that
  1922.     contains doctest tests to a unittest test case.  If any of the
  1923.     tests in a doc string fail, then the test case fails.  An exception
  1924.     is raised showing the name of the file containing the test and a
  1925.     (sometimes approximate) line number.
  1926.  
  1927.     The `module` argument provides the module to be tested.  The argument
  1928.     can be either a module or a module name.
  1929.  
  1930.     If no argument is given, the calling module is used.
  1931.  
  1932.     A number of options may be provided as keyword arguments:
  1933.  
  1934.     setUp
  1935.       A set-up function.  This is called before running the
  1936.       tests in each file. The setUp function will be passed a DocTest
  1937.       object.  The setUp function can access the test globals as the
  1938.       globs attribute of the test passed.
  1939.  
  1940.     tearDown
  1941.       A tear-down function.  This is called after running the
  1942.       tests in each file.  The tearDown function will be passed a DocTest
  1943.       object.  The tearDown function can access the test globals as the
  1944.       globs attribute of the test passed.
  1945.  
  1946.     globs
  1947.       A dictionary containing initial global variables for the tests.
  1948.  
  1949.     optionflags
  1950.        A set of doctest option flags expressed as an integer.
  1951.     '''
  1952.     if test_finder is None:
  1953.         test_finder = DocTestFinder()
  1954.     
  1955.     module = _normalize_module(module)
  1956.     tests = test_finder.find(module, globs = globs, extraglobs = extraglobs)
  1957.     if globs is None:
  1958.         globs = module.__dict__
  1959.     
  1960.     if not tests:
  1961.         raise ValueError(module, 'has no tests')
  1962.     
  1963.     tests.sort()
  1964.     suite = unittest.TestSuite()
  1965.     for test in tests:
  1966.         if len(test.examples) == 0:
  1967.             continue
  1968.         
  1969.         if not test.filename:
  1970.             filename = module.__file__
  1971.             if filename[-4:] in ('.pyc', '.pyo'):
  1972.                 filename = filename[:-1]
  1973.             
  1974.             test.filename = filename
  1975.         
  1976.         suite.addTest(DocTestCase(test, **options))
  1977.     
  1978.     return suite
  1979.  
  1980.  
  1981. class DocFileCase(DocTestCase):
  1982.     
  1983.     def id(self):
  1984.         return '_'.join(self._dt_test.name.split('.'))
  1985.  
  1986.     
  1987.     def __repr__(self):
  1988.         return self._dt_test.filename
  1989.  
  1990.     __str__ = __repr__
  1991.     
  1992.     def format_failure(self, err):
  1993.         return 'Failed doctest test for %s\n  File "%s", line 0\n\n%s' % (self._dt_test.name, self._dt_test.filename, err)
  1994.  
  1995.  
  1996.  
  1997. def DocFileTest(path, module_relative = True, package = None, globs = None, parser = DocTestParser(), encoding = None, **options):
  1998.     if globs is None:
  1999.         globs = { }
  2000.     else:
  2001.         globs = globs.copy()
  2002.     if package and not module_relative:
  2003.         raise ValueError('Package may only be specified for module-relative paths.')
  2004.     
  2005.     (doc, path) = _load_testfile(path, package, module_relative)
  2006.     if '__file__' not in globs:
  2007.         globs['__file__'] = path
  2008.     
  2009.     name = os.path.basename(path)
  2010.     if encoding is not None:
  2011.         doc = doc.decode(encoding)
  2012.     
  2013.     test = parser.get_doctest(doc, globs, name, path, 0)
  2014.     return DocFileCase(test, **options)
  2015.  
  2016.  
  2017. def DocFileSuite(*paths, **kw):
  2018.     '''A unittest suite for one or more doctest files.
  2019.  
  2020.     The path to each doctest file is given as a string; the
  2021.     interpretation of that string depends on the keyword argument
  2022.     "module_relative".
  2023.  
  2024.     A number of options may be provided as keyword arguments:
  2025.  
  2026.     module_relative
  2027.       If "module_relative" is True, then the given file paths are
  2028.       interpreted as os-independent module-relative paths.  By
  2029.       default, these paths are relative to the calling module\'s
  2030.       directory; but if the "package" argument is specified, then
  2031.       they are relative to that package.  To ensure os-independence,
  2032.       "filename" should use "/" characters to separate path
  2033.       segments, and may not be an absolute path (i.e., it may not
  2034.       begin with "/").
  2035.  
  2036.       If "module_relative" is False, then the given file paths are
  2037.       interpreted as os-specific paths.  These paths may be absolute
  2038.       or relative (to the current working directory).
  2039.  
  2040.     package
  2041.       A Python package or the name of a Python package whose directory
  2042.       should be used as the base directory for module relative paths.
  2043.       If "package" is not specified, then the calling module\'s
  2044.       directory is used as the base directory for module relative
  2045.       filenames.  It is an error to specify "package" if
  2046.       "module_relative" is False.
  2047.  
  2048.     setUp
  2049.       A set-up function.  This is called before running the
  2050.       tests in each file. The setUp function will be passed a DocTest
  2051.       object.  The setUp function can access the test globals as the
  2052.       globs attribute of the test passed.
  2053.  
  2054.     tearDown
  2055.       A tear-down function.  This is called after running the
  2056.       tests in each file.  The tearDown function will be passed a DocTest
  2057.       object.  The tearDown function can access the test globals as the
  2058.       globs attribute of the test passed.
  2059.  
  2060.     globs
  2061.       A dictionary containing initial global variables for the tests.
  2062.  
  2063.     optionflags
  2064.       A set of doctest option flags expressed as an integer.
  2065.  
  2066.     parser
  2067.       A DocTestParser (or subclass) that should be used to extract
  2068.       tests from the files.
  2069.  
  2070.     encoding
  2071.       An encoding that will be used to convert the files to unicode.
  2072.     '''
  2073.     suite = unittest.TestSuite()
  2074.     if kw.get('module_relative', True):
  2075.         kw['package'] = _normalize_module(kw.get('package'))
  2076.     
  2077.     for path in paths:
  2078.         suite.addTest(DocFileTest(path, **kw))
  2079.     
  2080.     return suite
  2081.  
  2082.  
  2083. def script_from_examples(s):
  2084.     """Extract script from text with examples.
  2085.  
  2086.        Converts text with examples to a Python script.  Example input is
  2087.        converted to regular code.  Example output and all other words
  2088.        are converted to comments:
  2089.  
  2090.        >>> text = '''
  2091.        ...       Here are examples of simple math.
  2092.        ...
  2093.        ...           Python has super accurate integer addition
  2094.        ...
  2095.        ...           >>> 2 + 2
  2096.        ...           5
  2097.        ...
  2098.        ...           And very friendly error messages:
  2099.        ...
  2100.        ...           >>> 1/0
  2101.        ...           To Infinity
  2102.        ...           And
  2103.        ...           Beyond
  2104.        ...
  2105.        ...           You can use logic if you want:
  2106.        ...
  2107.        ...           >>> if 0:
  2108.        ...           ...    blah
  2109.        ...           ...    blah
  2110.        ...           ...
  2111.        ...
  2112.        ...           Ho hum
  2113.        ...           '''
  2114.  
  2115.        >>> print script_from_examples(text)
  2116.        # Here are examples of simple math.
  2117.        #
  2118.        #     Python has super accurate integer addition
  2119.        #
  2120.        2 + 2
  2121.        # Expected:
  2122.        ## 5
  2123.        #
  2124.        #     And very friendly error messages:
  2125.        #
  2126.        1/0
  2127.        # Expected:
  2128.        ## To Infinity
  2129.        ## And
  2130.        ## Beyond
  2131.        #
  2132.        #     You can use logic if you want:
  2133.        #
  2134.        if 0:
  2135.           blah
  2136.           blah
  2137.        #
  2138.        #     Ho hum
  2139.        <BLANKLINE>
  2140.        """
  2141.     output = []
  2142.     for piece in DocTestParser().parse(s):
  2143.         if isinstance(piece, Example):
  2144.             output.append(piece.source[:-1])
  2145.             want = piece.want
  2146.             if want:
  2147.                 output.append('# Expected:')
  2148.                 [] += [ '## ' + l for l in want.split('\n')[:-1] ]
  2149.             
  2150.         want
  2151.         [] += [ _comment_line(l) for l in piece.split('\n')[:-1] ]
  2152.     
  2153.     while output and output[-1] == '#':
  2154.         output.pop()
  2155.         continue
  2156.         []
  2157.     while output and output[0] == '#':
  2158.         output.pop(0)
  2159.         continue
  2160.         output
  2161.     return '\n'.join(output) + '\n'
  2162.  
  2163.  
  2164. def testsource(module, name):
  2165.     '''Extract the test sources from a doctest docstring as a script.
  2166.  
  2167.     Provide the module (or dotted name of the module) containing the
  2168.     test to be debugged and the name (within the module) of the object
  2169.     with the doc string with tests to be debugged.
  2170.     '''
  2171.     module = _normalize_module(module)
  2172.     tests = DocTestFinder().find(module)
  2173.     test = _[1]
  2174.     test = test[0]
  2175.     testsrc = script_from_examples(test.docstring)
  2176.     return testsrc
  2177.  
  2178.  
  2179. def debug_src(src, pm = False, globs = None):
  2180.     """Debug a single doctest docstring, in argument `src`'"""
  2181.     testsrc = script_from_examples(src)
  2182.     debug_script(testsrc, pm, globs)
  2183.  
  2184.  
  2185. def debug_script(src, pm = False, globs = None):
  2186.     '''Debug a test script.  `src` is the script, as a string.'''
  2187.     import pdb
  2188.     srcfilename = tempfile.mktemp('.py', 'doctestdebug')
  2189.     f = open(srcfilename, 'w')
  2190.     f.write(src)
  2191.     f.close()
  2192.     
  2193.     try:
  2194.         if globs:
  2195.             globs = globs.copy()
  2196.         else:
  2197.             globs = { }
  2198.         if pm:
  2199.             
  2200.             try:
  2201.                 execfile(srcfilename, globs, globs)
  2202.             print sys.exc_info()[1]
  2203.             pdb.post_mortem(sys.exc_info()[2])
  2204.  
  2205.         else:
  2206.             pdb.run('execfile(%r)' % srcfilename, globs, globs)
  2207.     finally:
  2208.         os.remove(srcfilename)
  2209.  
  2210.  
  2211.  
  2212. def debug(module, name, pm = False):
  2213.     '''Debug a single doctest docstring.
  2214.  
  2215.     Provide the module (or dotted name of the module) containing the
  2216.     test to be debugged and the name (within the module) of the object
  2217.     with the docstring with tests to be debugged.
  2218.     '''
  2219.     module = _normalize_module(module)
  2220.     testsrc = testsource(module, name)
  2221.     debug_script(testsrc, pm, module.__dict__)
  2222.  
  2223.  
  2224. class _TestClass:
  2225.     """
  2226.     A pointless class, for sanity-checking of docstring testing.
  2227.  
  2228.     Methods:
  2229.         square()
  2230.         get()
  2231.  
  2232.     >>> _TestClass(13).get() + _TestClass(-12).get()
  2233.     1
  2234.     >>> hex(_TestClass(13).square().get())
  2235.     '0xa9'
  2236.     """
  2237.     
  2238.     def __init__(self, val):
  2239.         '''val -> _TestClass object with associated value val.
  2240.  
  2241.         >>> t = _TestClass(123)
  2242.         >>> print t.get()
  2243.         123
  2244.         '''
  2245.         self.val = val
  2246.  
  2247.     
  2248.     def square(self):
  2249.         """square() -> square TestClass's associated value
  2250.  
  2251.         >>> _TestClass(13).square().get()
  2252.         169
  2253.         """
  2254.         self.val = self.val ** 2
  2255.         return self
  2256.  
  2257.     
  2258.     def get(self):
  2259.         """get() -> return TestClass's associated value.
  2260.  
  2261.         >>> x = _TestClass(-42)
  2262.         >>> print x.get()
  2263.         -42
  2264.         """
  2265.         return self.val
  2266.  
  2267.  
  2268. __test__ = {
  2269.     '_TestClass': _TestClass,
  2270.     'string': '\n                      Example of a string object, searched as-is.\n                      >>> x = 1; y = 2\n                      >>> x + y, x * y\n                      (3, 2)\n                      ',
  2271.     'bool-int equivalence': '\n                                    In 2.2, boolean expressions displayed\n                                    0 or 1.  By default, we still accept\n                                    them.  This can be disabled by passing\n                                    DONT_ACCEPT_TRUE_FOR_1 to the new\n                                    optionflags argument.\n                                    >>> 4 == 4\n                                    1\n                                    >>> 4 == 4\n                                    True\n                                    >>> 4 > 4\n                                    0\n                                    >>> 4 > 4\n                                    False\n                                    ',
  2272.     'blank lines': "\n                Blank lines can be marked with <BLANKLINE>:\n                    >>> print 'foo\\n\\nbar\\n'\n                    foo\n                    <BLANKLINE>\n                    bar\n                    <BLANKLINE>\n            ",
  2273.     'ellipsis': "\n                If the ellipsis flag is used, then '...' can be used to\n                elide substrings in the desired output:\n                    >>> print range(1000) #doctest: +ELLIPSIS\n                    [0, 1, 2, ..., 999]\n            ",
  2274.     'whitespace normalization': '\n                If the whitespace normalization flag is used, then\n                differences in whitespace are ignored.\n                    >>> print range(30) #doctest: +NORMALIZE_WHITESPACE\n                    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n                     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n                     27, 28, 29]\n            ' }
  2275.  
  2276. def _test():
  2277.     r = unittest.TextTestRunner()
  2278.     r.run(DocTestSuite())
  2279.  
  2280. if __name__ == '__main__':
  2281.     _test()
  2282.  
  2283.